import React, { Component } from 'react';
import {
    Form, Icon, Input, Radio,
    Button, Dropdown, Menu, Table,
    Tag, Pagination, notification,
    Modal, Row, Col, Select, Upload
} from 'antd';
import axios from '../axios.config';
import JavascriptCommon from '../javascript.common';
import md5 from "js-md5";

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [{
                title: "姓名",
                width: 185,
                dataIndex: "ZK_NAME",
                sorter: true
            }, {
                title: "单位",
                dataIndex: "ZK_DEPARTMENT",
                sorter: true
            }, {
                title: "电子邮箱",
                dataIndex: "ZK_EMAIL",
                sorter: true
            }, {
                title: "电话号码",
                dataIndex: "ZK_PHONE",
                sorter: true
            }, {
                title: "角色",
                dataIndex: "ZK_ROLE",
                sorter: true,
                render: text => { return text.indexOf('管理员') > -1 ? <Tag color="blue">{text}</Tag> : <span>{text}</span> }
            }, {
                title: "最后修改",
                dataIndex: "EB_LASTMODIFY_DATETIME",
                sorter: true,
                render: text => this.formatterDate(text, "-")
            }, {
                title: "操作",
                width: 120,
                render: (text, record, index) => (<Button.Group>
                    <Button type="primary" icon="edit" onClick={() => { this.getRecord(record, index); }} />
                    <Button type="primary" icon="delete" onClick={() => { this.delRecord(record, index); }} />
                </Button.Group>)
            }],
            selection: [],
            records: [],
            tableParam: {
                keyword: "",
                _keyword: "",
                prop: "",
                order: "",
                pagesize: 15,
                pageno: 1,
                total: 0,
                loading: false,
                dropdown: [
                    { key: "ZK_NAME", value: "姓名" },
                    { key: "ZK_DEPARTMENT", value: "单位" },
                    { key: "ZK_EMAIL", value: "电子邮箱" },
                    { key: "ZK_PHONE", value: "电话号码" }
                ],
                keycurrent: 0
            },
            recordForm: {
                flag: true,
                record: {},
                visible: false,
                index: -1
            },
            roles: []
        };
    }
    componentDidMount() {
        this.query();
        this.bindRole();
    }
    query() {
        this.state.tableParam.loading = true;
        this.setState({ tableParam: this.state.tableParam });
        axios.get("Http/Msg/UserServer.ashx?method=Backend_GetUserList", {
            params: {
                KEYWORD: this.state.tableParam.keyword,
                TYPE: this.state.tableParam.dropdown[this.state.tableParam.keycurrent].key,
                PROP: this.state.tableParam.prop,
                ORDER: this.state.tableParam.order,
                PAGESIZE: this.state.tableParam.pagesize,
                PAGENO: this.state.tableParam.pageno
            }
        }).then(res => {
            this.state.tableParam.loading = false;
            this.setState({ tableParam: this.state.tableParam });
            if (res.data.flag === "True") {
                this.state.tableParam.total = parseInt(res.data.message);
                this.setState({ records: res.data.result });
            }
        });
    }
    currentChange(currentPage) {
        if (this.state.tableParam.pageno !== currentPage) {
            this.state.tableParam.pageno = currentPage;
            this.setState({ tableParam: this.state.tableParam }, () => {
                this.query();
            });
        }
    }
    sortChange(s) {
        if ("field" in s && s.field && s.order) {
            this.state.tableParam.prop = s.field;
            this.state.tableParam.order = s.order + "ing"
            this.state.tableParam.pageno = 1;
            this.query();
        }
    }
    formatterDate(value) {
        return JavascriptCommon.ChangeDateFormat_hhmmss(value, "-");
    }
    delRecord(record, index) {
        Modal.confirm({
            title: "提示",
            content: "确认删除该记录吗?",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/UserServer.ashx?method=Backend_DeleteUser", { IDS: record.ZK_ID }).then(res => {
                    if (res.data.flag === "True") {
                        this.state.records.splice(index, 1);
                        this.setState({ records: this.state.records }, () => {
                            notification.success({
                                message: "成功",
                                description: "已成功删除用户" + record.ZK_NAME
                            });
                        });
                    }
                });
            }
        });
    }
    batchDelete() {
        Modal.confirm({
            title: "提示",
            content: "确认删除所选的记录吗?",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/UserServer.ashx?method=Backend_DeleteUser", { IDS: this.state.selection.join(",") }).then(res => {
                    if (res.data.flag === "True") {
                        notification.success({
                            message: "成功",
                            description: "成功删除多条记录(一秒后将自动刷新页面)"
                        });
                        setTimeout(() => {
                            window.location.reload();
                        }, 1200);
                    }
                });
            }
        });
    }
    getRecord(record, index) {
        axios.get("Http/Msg/UserServer.ashx?method=Backend_GetUserInfo", { params: { UID: record.ZK_ID } }).then(res => {
            if (res.data.flag === "True") {
                res.data.result.ZK_PASSWORD = "";
                this.state.recordForm.record = res.data.result;
                this.state.recordForm.flag = false;
                this.state.recordForm.visible = true;
                this.state.recordForm.index = index;
                this.setState({ recordForm: this.state.recordForm });
            }
        });
    }
    bindRole() {
        axios.get("Http/Msg/HomeServer.ashx?method=Backend_BindRoleList").then(res => {
            if (res.data.flag === "True") {
                let roles = [];
                res.data.result.forEach(item => {
                    roles.push({ value: item.ZK_ID, key: item.ZK_ROLE });
                });
                this.setState({ roles: roles });
            }
        });
    }
    insertRecord(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) { return false; }
            for (let key in values) {
                this.state.recordForm.record[key] = values[key];
            }
            axios.post("Http/Msg/UserServer.ashx?method=Backend_InsertUser", this.state.recordForm.record).then(res => {
                if (res.data.flag === "True") {
                    notification.success({
                        message: "成功",
                        description: "新增用户:" + this.state.recordForm.record.ZK_NAME + "(一秒后将自动刷新页面)"
                    });
                    this.state.roles.forEach(role => {
                        if (role.value === this.state.recordForm.record.ZK_ROLE) {
                            this.state.recordForm.record.ZK_ROLE = role.key;
                            return false;
                        }
                    });
                    this.state.recordForm.visible = false;
                    this.state.records.unshift(this.state.recordForm.record);
                    this.setState({ recordForm: this.state.recordForm, records: this.state.records });
                    setTimeout(() => { window.location.reload(); }, 1200);
                }
            });
        });
    }
    updateRecord(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) { return false; }
            values.ZK_PASSWORD = values.ZK_PASSWORD && md5(values.ZK_PASSWORD);
            for (let key in values) {
                this.state.recordForm.record[key] = values[key];
            }
            axios.post("Http/Msg/UserServer.ashx?method=Backend_UpdateUser", this.state.recordForm.record).then(res => {
                if (res.data.flag === "True") {
                    notification.success({
                        message: "成功",
                        description: "更新用户信息：" + this.state.recordForm.record.ZK_NAME
                    });
                    this.state.roles.forEach(role => {
                        if (role.value === this.state.recordForm.record.ZK_ROLE) {
                            this.state.recordForm.record.ZK_ROLE = role.key;
                            return false;
                        }
                    });
                    this.state.recordForm.visible = false;
                    this.state.records[this.state.recordForm.index] = this.state.recordForm.record;
                    this.setState({ recordForm: this.state.recordForm, records: this.state.records });
                }
            });
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div id="user_temp">
                <div className="toolbar">
                    <Form layout="inline">
                        <Form.Item>
                            <Input
                                placeholder={"请输入关键字（" + this.state.tableParam.dropdown[this.state.tableParam.keycurrent].value + "）"}
                                value={this.state.tableParam._keyword}
                                onChange={e => { this.state.tableParam._keyword = e.target.value; this.setState({ tableParam: this.state.tableParam }); }}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Dropdown overlay={<Menu>
                                {this.state.tableParam.dropdown.map((item, index) => (
                                    <Menu.Item key={item.key} onClick={() => {
                                        this.state.tableParam.pageno = 1;
                                        this.state.tableParam.keycurrent = index;
                                        this.state.tableParam.keyword = this.state.tableParam._keyword;
                                        this.setState({ tableParam: this.state.tableParam }, () => { this.query(); });
                                    }} >
                                        {this.state.tableParam.keycurrent === index ? <b>{item.value}</b> : item.value}
                                    </Menu.Item>
                                ))}
                            </Menu>}>
                                <Button type="primary" onClick={() => {
                                    this.state.tableParam.pageno = 1;
                                    this.state.tableParam.keyword = this.state.tableParam._keyword;
                                    this.setState({ tableParam: this.state.tableParam }, () => { this.query(); });
                                }} >
                                    <Icon type="search" />查询<Icon type="down" />
                                </Button>
                            </Dropdown>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" onClick={() => {
                                this.state.recordForm.flag = true;
                                this.state.recordForm.record = {};
                                this.state.recordForm.visible = true;
                                this.setState({ recordForm: this.state.recordForm });
                            }}>新增</Button>
                        </Form.Item>
                    </Form>
                </div>
                <Table
                    columns={this.state.columns}
                    dataSource={this.state.records}
                    rowKey={record => record.ZK_ID}
                    loading={this.state.tableParam.loading}
                    pagination={false}
                    rowSelection={{ onChange: keys => { this.setState({ selection: keys }); } }}
                    onChange={(p, f, s) => { this.sortChange(s); }}>
                </Table>
                <div className="botton_toolbar">
                    <Button type="danger" icon="delete" disabled={this.state.selection.length === 0} onClick={() => { this.batchDelete(); }}>
                        批量删除{this.state.selection.length > 0 ? "(共" + this.state.selection.length + "条)" : ""}
                    </Button>
                    <Pagination
                        size="small"
                        style={{ float: "right" }}
                        total={this.state.tableParam.total}
                        current={this.state.tableParam.pageno}
                        pageSize={this.state.tableParam.pagesize}
                        showQuickJumper
                        showTotal={total => (<span className="recordtotal">共{total}条记录</span>)}
                        onChange={page => { this.currentChange(page); }}
                    />
                </div>
                <Modal
                    title={this.state.recordForm.flag ? "新增" : "编辑"}
                    visible={this.state.recordForm.visible}
                    footer={null}
                    maskClosable={false}
                    destroyOnClose={true}
                    onCancel={() => { this.state.recordForm.visible = false; this.setState({ recordForm: this.state.recordForm }); }}
                >
                    <Form onSubmit={e => {
                        if (this.state.recordForm.flag) {
                            this.insertRecord(e)
                        } else {
                            this.updateRecord(e);
                        }
                    }}>
                        <Form.Item
                            label="用户名"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            <Row>
                                <Col span={12}>
                                    {getFieldDecorator("ZK_NAME", {
                                        initialValue: this.state.recordForm.record.ZK_NAME,
                                        rules: [{ required: true, message: "请输入姓名" }]
                                    })(<Input />)}
                                </Col>
                                <Col span={8}>
                                    <img
                                        src={this.state.recordForm.record.ZK_HEAD_PORTRAIT}
                                        alt={this.state.recordForm.record.ZK_NAME}
                                        style={{ width: "64px", height: "64px", boxShadow: "0 0 5px gray", margin: "-12px auto", display: "block", borderRadius: "4px" }}
                                    />
                                </Col>
                                <Col span={4}>
                                    <Upload action="/upload.do">
                                        <Button type="ghost" icon="upload" />
                                    </Upload>
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item
                            label="密　码"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_PASSWORD", {
                                initialValue: this.state.recordForm.record.ZK_PASSWORD,
                                rules: [{ required: this.state.recordForm.flag, message: "请输入密码" }]
                            })(<Input type="password" placeholder={this.state.recordForm.flag ? '新增用户时必须填写密码' : '密码为空时默认不修改'} />)}
                        </Form.Item>
                        <Form.Item
                            label="性　别"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_SEX", {
                                initialValue: this.state.recordForm.record.ZK_SEX || "男"
                            })(<Radio.Group>
                                <Radio value="男">男</Radio>
                                <Radio value="女">女</Radio>
                            </Radio.Group>)}
                        </Form.Item>
                        <Form.Item
                            label="角　色"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_ROLE", {
                                initialValue: this.state.recordForm.record.ZK_ROLE,
                                rules: [{ required: true, message: "请选择角色" }]
                            })(<Select>
                                {this.state.roles.map(item => (
                                    <Select.Option value={item.value} key={item.value}>{item.key}</Select.Option>
                                ))}
                            </Select>)}
                        </Form.Item>
                        <Form.Item
                            label="单　位"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_DEPARTMENT", {
                                initialValue: this.state.recordForm.record.ZK_DEPARTMENT,
                                rules: [{ required: true, message: "请输入单位" }]
                            })(<Input />)}

                        </Form.Item>
                        <Form.Item
                            label="电子邮箱"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_EMAIL", {
                                initialValue: this.state.recordForm.record.ZK_EMAIL,
                                rules: [{ required: true, message: "请输入电子邮箱" }]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item
                            label="电话号码"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_PHONE", {
                                initialValue: this.state.recordForm.record.ZK_PHONE,
                                rules: [{ required: true, message: "请输入电话号码" }]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item
                            label="备　注"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_REMARK", {
                                initialValue: this.state.recordForm.record.ZK_REMARK
                            })(<Input.TextArea />)}
                        </Form.Item>
                        <Form.Item>
                            <Row style={{ textAlign: "center" }}>
                                <Col span={12}>
                                    <Button icon="rollback" onClick={() => {
                                        this.state.recordForm.visible = false; this.setState({ recordForm: this.state.recordForm });
                                    }}>
                                        返回
                                    </Button>
                                </Col>
                                <Col span={12}>
                                    <Button type="primary" htmlType="submit" icon="save">保存</Button>
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        );
    }
}

User = Form.create()(User);

export default User;
